package com.yuanfeng.job.job;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuanfeng.commoms.dto.order.WapGoodsSaleSumDTO;
import com.yuanfeng.job.dto.OrderStatusDTO;
import com.yuanfeng.job.entity.JobPlatformEntity;
import com.yuanfeng.job.feign.ActivityServiceClient;
import com.yuanfeng.job.feign.GoodsServiceClient;
import com.yuanfeng.job.service.JobPlatformService;
import com.yuanfeng.job.service.UpdateOrderStatusService;
import com.yuanfeng.job.service.UpdateRecordStatusService;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 更新超过1天 未支付订单
 */
public class UpdateTimeoutOrderStatusJob implements BaseJob {

	private static final Logger logger = LoggerFactory.getLogger(UpdateTimeoutOrderStatusJob.class);

	@Autowired
	private UpdateOrderStatusService updateOrderstatusService;

	@Autowired
	private UpdateRecordStatusService updateRecordStatusService;

	@Autowired
	private ActivityServiceClient activityServiceClient;

	@Autowired
	private GoodsServiceClient goodsServiceClient;

	@Autowired
	private JobPlatformService jobPlatformService;

	//1.1 返回超时订单红包
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		// 查询超过15分钟未支付订单号
		//List<String> orderIds = updateOrderstatusService.listTimeoutOrder();
		//查询超时时间
		Integer time = 60 * 24;
		String minutes = time.toString();
		JobPlatformEntity jobPlatformEntity=jobPlatformService.getOne(new LambdaQueryWrapper<JobPlatformEntity>()
											.eq(JobPlatformEntity::getInvokeTarget,"com.yuanfeng.job.job.UpdateTimeoutOrderStatusJob"));


		String timeOutPeriod = jobPlatformEntity.getTimeOutPeriod();
		if (!StringUtils.isEmpty(timeOutPeriod)) {
			minutes = timeOutPeriod;
		}
		//查询超过n分钟额订单
		List<String> orderIds = updateOrderstatusService.listTimeoutOrder2(minutes);


		List<WapGoodsSaleSumDTO> goodsDetailsList = new ArrayList<WapGoodsSaleSumDTO>();
		for (String orderId : orderIds) {

			List<WapGoodsSaleSumDTO> wapGood = updateOrderstatusService.queryGoodsXinXi(orderId);
			for (WapGoodsSaleSumDTO wapOne : wapGood) {
				goodsDetailsList.add(wapOne);
			}
		}

//		Map<String, List<WapGoodsSaleSumDTO>> goodsSaleSum = new HashMap<String, List<WapGoodsSaleSumDTO>>();
//		goodsSaleSum.put("goodsDetails", goodsDetailsList);
		//mallsServices.updateSaleSum(goodsSaleSum);
		//修改商品库存
		goodsServiceClient.updateGoodsStock(goodsDetailsList);

		//返回红包
		List<OrderStatusDTO> orderStatus = updateOrderstatusService.listTimeoutOrderDetail2(minutes);
		for (OrderStatusDTO orderStatu : orderStatus) {
			//退还红包
			if (orderStatu.getRedpacketCode() != null) {
				List<Integer> orderStatusList = updateOrderstatusService.queryOrderStatus(orderStatu.getPaymentNumber());// 查询订单状态
				Map<String, Object> codeMap = new HashMap<String, Object>();
				codeMap.put("redpacketId", orderStatu.getRedpacketCode());
				codeMap.put("platformVoucherCode",orderStatu.getPlatformCouponCode());
				System.out.println(orderStatu.getPlatformCouponCode());
				codeMap.put("type","1");
				Set set = new HashSet(orderStatusList);
				if(set.size() == 1){
					activityServiceClient.updateSalesPrm(codeMap);
					if(orderStatu.getVoucherCode() != null && !orderStatu.getVoucherCode().isEmpty()){
						List<String> voucherCodeList = Arrays.asList(orderStatu.getVoucherCode().split(","));
						Map<String,Object> voucherCodeMap = new HashMap<String,Object>();
						voucherCodeMap.put("voucherId",voucherCodeList);
						voucherCodeMap.put("type","1");
						activityServiceClient.updateSalesPrm(voucherCodeMap);
					}
				}
			}else{
				if(orderStatu.getVoucherCode() != null && !orderStatu.getVoucherCode().isEmpty()){
					List<String> voucherCodeList = Arrays.asList(orderStatu.getVoucherCode().split(","));
					Map<String,Object> voucherCodeMap = new HashMap<String,Object>();
					voucherCodeMap.put("voucherId",voucherCodeList);
					voucherCodeMap.put("platformVoucherCode",orderStatu.getPlatformCouponCode());
					voucherCodeMap.put("type","1");
					activityServiceClient.updateSalesPrm(voucherCodeMap);
				}
			}

		}

        logger.info("待更新的超过24小时未支付的订单号orderId：" + orderIds);

		// 更新超过24小时未支付订单（orderBase表）
		Integer countTimeoutOrderBase = updateOrderstatusService.updateTimeoutOrder2(minutes);
		logger.info("更新所有超时未支付订单(orderBase表)，更新数量为：" + countTimeoutOrderBase);

		// 更新超过24小时未支付订单（orderGoods表）
		logger.info("更新所有超时未支付订单(ordergoods表)");
		for (String orderId : orderIds) {
			updateOrderstatusService.updateTimeoutOrderGoods(orderId);

			logger.info("更新所有超时未支付订单关联的审批表(odb_order_approval表)");

			// updateOrderstatusService.editApprovalId(orderId);
		}

		// 根据paymentOrder更新所有超时订单记录(Record表)
		Integer countRecord = 0;
		for (String orderId : orderIds) {
			countRecord += updateRecordStatusService.updateTimeoutRecord(orderId);
		}
		logger.info("更新所有超时未支付订单记录，更新数量为：" + countRecord);

		// 根据paymentOrder更新所有超时订单记录(Trade表)
		logger.info("更新所有超时未支付订单Trade：");
		for (String orderId : orderIds) {
			countRecord += updateRecordStatusService.updateTimeoutTrade(orderId);
		}

	}

}
